<?php

namespace app\system\controller\corp;

use app\common\controller\System;
use app\system\controller\daily\Throwable;
use ba\Tree;
use hehe\Str;
use hehe\Trade;
use think\facade\Db;
use think\facade\Lang;


class Supplier extends System {
    /**
     * Goods模型对象
     * @var object
     */
    protected object $model;

    protected string|array $defaultSortField = 'id,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['corp_name_cn', 'corp_name_ko', 'corp_name_en'];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\system\model\corp\Supplier();
    }


    protected function getIndustry($where = []): array {
        $initKey = $this->request->get("initKey/s", 'id');
        if ($this->request->has('quickSearch', '')) {
            $keyword = explode(' ', $this->request->request('quickSearch', ''));
            foreach ($keyword as $item) {
                $where[] = ['name', 'like', '%' . $item . '%'];
            }
        }

        $isTree = $this->request->param('isTree', true);
        $initValue = $this->request->get('initValue/a', []);
        $initValue = array_filter($initValue);
        $assembleTree = $isTree && !$initValue;
        if ($initValue) {
            $where[] = [$initKey, 'in', $initValue];
        }
        $result = Db::name('industry_old_category')
            ->where($where)
            ->order('weigh desc,id asc')
            ->select()->toArray();

        $this->tree = Tree::instance();

        return $assembleTree ? $this->tree->assembleChild($result) : $result;
    }



    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }



        $this->withJoinTable = ['category'];
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->with(['category' => function($query){
                $query->with(['parentCategory']);
            }])
            ->alias($alias)
            ->where($where);
        $param = $this->request->param();

//        print_r($param);die;

        if(isset($param['form'])){
            if(!empty($param['form']['keyword'])){
                $res = $res->where('corp_name_cn', 'like', '%' . trim($param['form']['keyword']) . '%');
            }
            if(!empty($param['form']['category'])){
                $category = [];
                foreach($param['form']['category'] as $val){
                    $category[] = $val[count($val) - 1];
                }
                $res = $res->whereIn('category_id', $category);
            }
        }

        $param['type'] = empty($param['type']) ? 'local' : $param['type'];

        if(!empty($param['type'])){
            $res = $res->where(['type' => $param['type']]);
        }

        if($this->request->has('select')){
            $res->order('weigh desc, id desc');
        }else{
            $res->order($order);
        }


        $res = $res->paginate($limit);

        $langSet = Lang::getLangSet();

        $list = $res->items();
        $langSet = Lang::getLangSet();
        foreach($list as $key => $val){
            if($langSet != 'zh-cn'){
                $list[$key]['corp_name_cn'] = empty($val['corp_name_' . $langSet]) ? $val['corp_name_cn'] : $val['corp_name_' . $langSet];
            }
        }


        $this->success('', [
            'list' => $list,
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    public function add(): void {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $data['type'] = 'local';

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    /**
     * 添加进程
     */
    public function addProcess(): void {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $pid = $data['id'];
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            if(!empty($data['images'])) $data['images'] = implode(',', $data['images']);
            if(!empty($data['files'])) {
                $attachment = db::name('attachment')->whereIn('url', $data['files'])->select();
                $files = [];
                foreach($attachment as $val){
                    $files[] = [
                        'id' => $val['id'],
                        'url' => $val['url'],
                        'name' => $val['name']
                    ];
                }
                $data['files'] = json_encode($files);
            }

            $p_data = db::name('business')->where(['id' => $pid])->find();
            $data['pid'] = $p_data['pid'] == 0 ? $p_data['id'] : $p_data['pid'];

            $data['admin_id'] = $this->auth->id;

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    public function edit(): void
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
//            print_r($data); die;
            $data['type'] = empty($data['type']) ? null : implode(',', $data['type']);
            if(!empty($data['industry_old'])){
                $data['industry_old'] = implode(',', $data['industry_old']);
            }
//            print_r($data); die;
            $result = false;
            $this->model->startTrans();
            try {
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }
        $row = $row->toArray();
        if(!empty($row['files'])){
            $row['files'] =  json_decode($row['files'], true);
            $files = [];
            foreach($row['files'] as $val){
                $files[] = $val['name'];
            }
            $row['files'] = $files;
        }

        $row['type'] = empty($row['type']) ? [] : explode(',', $row['type']);

        $row['industry_old'] = empty($row['industry_old']) ? null : explode(',', $row['industry_old']);
        if($row['industry_old']){
            foreach($row['industry_old'] as $key => $val){
                $row['industry_old'][$key] = (int) $val;
            }
        }

//        foreach($row['industry_old'] as $key => $val){
//            foreach($val as $k => $v){
//                $row['industry_old'][$key][$k] = (int)$v;
//            }
//        }

        $this->success('', [
            'row' => $row,
            'industry' => $this->getIndustry()
        ]);
    }



    /**
     * 删除报价单
     */
    public function delQuotationFile(): void {
        $id = $this->request->param('id');
        $update = [
            'quotation_file' => null,
            'update_time' => $this->timestamp
        ];
        db::name('business_quotation')->where(['id' => $id])->update($update);
        $this->success();
    }

    /**
     * 上传报价单
     */
    public function setQuotationFile(): void{
        $param = $this->request->post();
//        print_r($param);
        $quotation_file = json_encode($param['quotation_file']);
        $update = [
            'quotation_file' => $quotation_file,
            'update_time' => $this->timestamp
        ];
        db::name('business_quotation')->where(['id' => $param['id']])->update($update);
        $this->success();
    }


    /**
     * 删除备注
     */
    public function delNote(){
        $param = $this->request->param();
        db::name('business_quotation_note')->where(['id' => $param['id']])->delete();
        $this->success();
    }

    /**
     * 添加备注
     */
    public function addNote(){
        $param = $this->request->param();
        $param['admin_id'] = $this->auth->id;
        $param['create_time'] = $this->timestamp;
        $note_id = db::name('business_quotation_note')->insertGetId($param);
        if($note_id){
            $this->success('', [
                'id' => $note_id,
                'content' => $param['content'],
                'admin' => [
                    'username' => $this->auth->username
                ]

            ]);
        }else{
            $this->error();
        }
    }

    /**
     * 隐藏报价
     */
    public function hideQuotation(){
        $param = $this->request->param();
        db::name('business_quotation')->where(['id' => $param['id']])->update(['hide' => 1]);
        $this->success();
    }
    /**
     * 显示报价
     */
    public function showQuotation(){
        $param = $this->request->param();
        db::name('business_quotation')->where(['id' => $param['id']])->update(['hide' => 0]);
        $this->success();
    }


































}